#!/usr/bin/env bash

APPLICATION_HOME=$(cd `dirname $0`; pwd)
CONF_FILE=$APPLICATION_HOME/application.conf
. $CONF_FILE

JAR_FILE=$APPLICATION_HOME/$JAR_NAME

# JAVA_OPTS
JAVA_OPTS="-server -Duser.dir=$APPLICATION_HOME"
JAVA_OPTS="${JAVA_OPTS} $JAVA_HEAP_OPTS"

# CONFIG_OPTS
CONFIG_OPTS="--spring.profiles.active=$PROFILE"
CONFIG_OPTS="${CONFIG_OPTS} $SPRING_BOOT_OPTS"

function start()
{
    java $JAVA_OPTS -jar $JAR_FILE $CONFIG_OPTS > /dev/null 2>&1 &
    echo start finished. pid num: $!
}

function stop()
{
    PID_NUM=$(ps aux |grep "${JAR_NAME}"|grep -v "grep"|awk '{print $2}')
    if [ ${PID_NUM} ] ; then
        echo pid num: ${PID_NUM}
        echo kill ${JAR_NAME}
        kill  ${PID_NUM}

    	echo sleep 10
    	sleep 10

        PID_NUM=$(ps aux |grep "${JAR_NAME}"|grep -v "grep"|awk '{print $2}')
    	if [ ${PID_NUM} ] ; then
        	echo kill -9 ${JAR_NAME}
       		kill -9 ${PID_NUM}
       	fi

       	echo stop finished.
    else
            echo ${JAR_NAME} not running
    fi
}

function status()
{
    PID_NUM=$(ps aux |grep "${JAR_NAME}"|grep -v "grep"|awk '{print $2}')
    if [ ${PID_NUM} ] ; then
        echo ${JAR_NAME} is running. pid num: ${PID_NUM}
    else
        echo ${JAR_NAME} not running
    fi
}


args=($@)

case "$1" in

    'start')
        start
        ;;

    'stop')
        stop
        ;;

    'restart')
        stop
        start
        ;;

    'status')
        status
        ;;
    *)
        echo "Usage: $0 { start | stop | restart | status}"
        exit 1
        ;;
esac